/**
 * Created by zhuang.haipeng on 2017/9/12.
 */
import React, {Component} from 'react';
import {DeviceEventEmitter, Image, ListView, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";

let languagesData = [
    {value: 'en', collectItem: I18n.t('default.english')},
    {value: 'ru', collectItem: I18n.t('default.russian')},
    {value: 'zh', collectItem: I18n.t('default.chines')},
    {value: 'uy', collectItem: I18n.t('default.uyghur')},

];
export default class extends React.Component {

    constructor(props) {
        super(props);

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds,
            isChecked: false,
            selectMap: new Map(),
            userInfo: null,
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                let parse = JSON.parse(result);

                this.setState({
                    userInfo: parse,
                    dataSource: this.state.dataSource.cloneWithRows(languagesData)
                });
            });


    }

    /*获取用户收货地址信息姐*/
    getLanguageInfo(lang) {

        let userInfo = this.state.userInfo;
        if (!userInfo) {
            return
        }

        let langs = '';
        for (i = 0; i < lang.length; i++) {
            langs += lang[i] + ',';
        }

        let formData = new FormData();
        formData.append("user_id", userInfo.main_user_id);
        formData.append("languages", langs);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    userInfo.languages = langs;

                    this.props.callback(userInfo);
                    this.props.navigator.pop();
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'))
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }


    render() {

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ScrollView>
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.editLanguage'), I18n.t('default.editYourLang'))}

                        <ListView
                            renderRow={this.renderRow.bind(this)}
                            dataSource={this.state.dataSource}

                        />
                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.onItemClick()
                        })}

                    </View>
                </ScrollView>
            </View>
        );
    }

    renderRow(rowData, sectionID, rowID) { // cell样式

        let map = this.state.selectMap;
        let isChecked = map.has(parseInt(rowID));
        // let language = lang.split(',');
        //
        // for (i = 0; i < language.length; i++) {
        // 	if (language[i] === rowData.collectItem) {
        //
        // 		this.selectItem(parseInt(rowID), rowData.collectItem, isChecked);
        // 		break
        // 	}
        // }


        // 选中的时候, 判断上一个索引不等于rowID的时候,不让他选中   **** 单选逻辑 ****
        // let isChecked = parseInt(rowID) == this.state.preIndex ?  map.has(parseInt(rowID)) : false; // 将rowID转成Int,然后将Int类型的ID当做Key传给Map

        return (
            <TouchableOpacity
                onPress={() => this.selectItem(parseInt(rowID), rowData.value, isChecked)}
                style={[StyleUtils.center, styles.itemBox]}>
                <Image
                    resizeMode="cover"
                    source={isChecked ? require("../../../res/images/ic_check_box.png") :
                        require("../../../res/images/ic_check_box_outline_blank.png")}
                    style={{resizeMode: 'cover'}}/>

                <Text
                    numberOfLines={1}
                    style={[styles.goodsText, StyleUtils.smallFont, {fontSize: 16}]}>
                    {rowData.collectItem}
                </Text>
            </TouchableOpacity>)
    };

    /*点击*/
    onItemClick() {
        let {selectMap} = this.state;
        let valueArr = [...selectMap.values()];
        if (valueArr.length !== 0) {
            CommonUtils.showLoading();

            this.getLanguageInfo(valueArr);
        } else {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectLanguage'))
        }
    };

    /*选择item*/
    selectItem(key, value, isChecked) { // 单选
        this.setState({
            isChecked: !this.state.isChecked,
            // preIndex: key  //  **** 单选逻辑 ****
        }, () => {
            let map = this.state.selectMap;
            if (isChecked) {
                map.delete(key, value) // 再次点击的时候,将map对应的key,value删除
            } else {
                // map = new Map() // ------>   **** 单选逻辑 ****
                map.set(key, value) // 勾选的时候,重置一下map的key和value
            }
            this.setState({selectMap: map})
        })
    }
};

const styles = StyleSheet.create({
    goodsText: {
        flex: 1,
        color: '#0f0f0f',
        paddingRight: 8,
        paddingLeft: 8
    },

    itemBox: {
        height: 80,
        borderBottomWidth: 1,
        borderBottomColor: '#eeeeee',
        flexDirection: 'row'
    },


});